package com.blazhovsky.mk.androidlan;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;

public class NitkaZaSkeniranje
{
	MainActivity context;

	public NitkaZaSkeniranje(MainActivity c)
	{
		context = c;
	}

	public void pocni()
	{
		new MyAsyncTaskAdresi().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
	}

	private class MyAsyncTaskAdresi extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params)
		{
			byte[] ad = { (byte) 192, (byte) 168, (byte) 1, 0 };
			for (int i = 0; i <= 255; i++)
			{
				InetAddress addr;
				ad[3] = (byte) i;
				try
				{
					addr = InetAddress.getByAddress(ad);
					System.out.println(addr.toString());
					if (addr.isReachable(100))
					{
						context.adresi.add(addr.getHostName().toString());
						System.out.println("Reachable");
					}
				}
				catch (UnknownHostException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);

			ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, context.adresi);
			context.adresiZaPrakjanje.setAdapter(arrayAdapter);
		}
	}
}
